package cn.easy.rest.filter;

import cn.easy.rest.dao.JedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@ContextHierarchy(@ContextConfiguration(name = "parent", locations = {"classpath:/META-INF/spring/applicationContext-*.xml"}))
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisClient jedisClient;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = null;
        String userInfo = null;
        String url = null;
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies == null && !httpServletRequest.getRequestURI().contains("login")) {
            //登录页面
            httpServletResponse.sendRedirect("/public/login");
            return false;
        }
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        //判断url
        url = requestURL.toString();
        Pattern pattern = Pattern.compile(".*?//.*?/(.*)/");
        Matcher matcher = pattern.matcher(url);
        matcher.find();
        if (matcher.group(1).equals("userManager")) {
            if (requestURL.toString().contains("login")) {
                return true;
            }
            for (Cookie c : cookies) {
                if (c.getName().equals("easylink_user_token")) {
                    token = c.getValue();
                    break;
                }
            }

            if (token == null) {
                //登录页面
                httpServletResponse.sendRedirect("/public/login");
                return false;
            }
            userInfo = jedisClient.get(token);
            if (userInfo == null) {
                httpServletResponse.sendRedirect("/public/login");
                return false;
            }
            //更新redis时间
            // jedisClient.expire(token, 30 * 60);
            jedisClient.expire(token, 60000*60);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
